<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */	

defined ('IN_AGORA') or die;

class TaskController extends AgoraAdminController
{
	function __construct()
	{
		parent::__construct();
		$board = & Model::getInstance('BoardModel');
		$this->forumList = $board->loadForumList(false);
	}

	function _default()
	{
		$num = 0;
		foreach ($this->forumList as $cat_id => $category) {
			$this->forumList[$cat_id]['list_number'] = $num;
			$this->forumList[$cat_id]['list_id'] = 'category_'.$category['cat_id'];
			$num += 1;

			$last_level = -1;
			foreach ($category['forums'] as $forum_id => $forum) {
				$this->forumList[$cat_id]['forums'][$forum_id]['not_last'] = true;
				if ($last_level != $forum['level']) {
					$first = true;
					$last_level = $forum['level'];

					if (isset($prev_forum)) {
						$prev_forum['not_last'] = true;
					}
				}
				if (!$first) {
					$this->forumList[$cat_id]['forums'][$forum_id]['not_first'] = true;
				} else {
					$this->forumList[$cat_id]['forums'][$forum_id]['not_first'] = false;
					$first = false;
				}
				$this->forumList[$cat_id]['forums'][$forum_id]['list_number'] = $num;
				$this->forumList[$cat_id]['forums'][$forum_id]['list_id'] = 'forum_'.$forum['id'];
				$num += 1;

				$prev_forum = & $forum;
			}
			if (isset($prev_forum))
				$prev_forum['not_last'] = false;
		}

		// pagination is for forums only (not for categories)
		$this->setPagination($num - count($this->forumList));

		// slice tree for pagination
		$total_number = 0;
		$sliced_forums = array();
		foreach ($this->forumList as $cat) {

			$forums = array();
			foreach ($cat['forums'] as $cur_forum) {
				if ($total_number >= $this->pagination->limitstart) {
					$forums[] = $cur_forum;
				}

				$total_number += 1;
				if ($total_number >= $this->pagination->limitstart + $this->pagination->per_page) {
					break;
				}
			}

			if ($total_number >= $this->pagination->limitstart + $this->pagination->per_page) {
				$cat['forums'] = $forums;

				$sliced_forums[] = $cat;
				break;
			}


			if ($total_number - count($cat['forums']) >= $this->pagination->limitstart) {
				// category is in current page
				$cat['forums'] = $forums;
				$sliced_forums[] = $cat;
			} elseif (!empty($forums)) {
				// we started on previous page
				$cat['cat_id'] = 0;
				$cat['forums'] = $forums;
				$sliced_forums[] = $cat;
			}
		}
		$this->view->assign('forums',$sliced_forums);
		$this->view->assign('forum_category_count',$num);
		$this->view->template = 'forums/list';
	}

	function orderup()
	{
		$cid = Agora::getPostVar('cid');
		if (!$cid || !array($cid)) $this->redirect();
		$item_id = $cid[0];
		if (strpos($item_id,'category_') === 0) {
			$cat_id = substr($item_id,9);
			$category_model = & Model::getInstance('CategoryModel');
			$category_model->orderUp($cat_id);
		} elseif (strpos($item_id,'forum_') === 0) {
			$forum_id = substr($item_id,6);
			$forum_model = & Model::getInstance('ForumModel');
			$forum_model->orderUp($forum_id);
		}
		$this->redirect();
	}

	function orderdown()
	{
		$cid = Agora::getPostVar('cid');
		if (!$cid || !array($cid)) $this->redirect();
		$item_id = $cid[0];
		if (strpos($item_id,'category_') === 0) {
			$cat_id = substr($item_id,9);
			$category_model = & Model::getInstance('CategoryModel');
			$category_model->orderDown($cat_id);
		} elseif (strpos($item_id,'forum_') === 0) {
			$forum_id = substr($item_id,6);
			$forum_model = & Model::getInstance('ForumModel');
			$forum_model->orderDown($forum_id);
		}
		$this->redirect();
	}

	function saveorder()
	{
		$category_model = & Model::getInstance('CategoryModel');
		$forum_model = & Model::getInstance('ForumModel');
		$order = Agora::getPostVar('order');

		$category_order = $order['category'];
		foreach ($category_order as $cat_id=>$disp_position) {
			$category_model->setOrder($cat_id,$disp_position);
		}
		$category_model->reorder();

		$forum_order = $order['forum'];
		foreach ($forum_order as $forum_id=>$disp_position) {
			$forum_model->setOrder($forum_id,$disp_position);
		}
		$forum_model->reorder();
		$this->redirect();
	}

	function cancel()
	{
		$this->redirect();
	}

	function edit()
	{
		$cid = Agora::getPostVar('cid');
		$id = array_shift($cid);
		
		if (strpos($id,'category_') === 0) {
			$cat_id = substr($id,9);
			$this->redirect('action=edit_category','category_id='.$cat_id);
		} elseif (strpos($id,'forum_') === 0) {
			$forum_id = substr($id,6);
			$this->redirect('action=edit_forum','forum_id='.$forum_id);
		} else {
			$this->redirect();
		}
	}

	function edit_forum($form=null)
	{
		$forum_id = Agora::getRequestVar('forum_id');

		$parents = array();
		foreach ($this->forumList as $category) {
			$parents['cat_'.$category['cat_id']] = $category['cat_name'];
			foreach ($category['forums'] as $forum) {
				if ($forum['id'] == $forum_id) continue;
				$parents['forum_'.$forum['id']] = str_repeat('&nbsp;&nbsp;',$forum['level']+1).$forum['forum_name'];
			}
		}
		$this->view->assign('parents',$parents);

		if ($form) {
			// error from previous edit
			$forum = $form;
		} else {
			$forum_model = &Model::getInstance('ForumModel');
			$forum = $forum_model->load($forum_id);
		}
		$forum['forum_id'] = $forum_id;
		
		$styles_model = & Model::getInstance('StylesModel');
		$styles = $styles_model->_loadAll();
		$styling=array();
		$styling[0]='default';
		foreach ($styles as $style) {
			$styling[$style['id']] = $style['ref_name'];
		}
		$this->view->assign('styling',$styling);

		if (!isset($forum['parent_forum_id'])) {
			$forum['parent_object_id'] = '-1';
		} elseif ($forum['parent_forum_id'] == '0') {
			$forum['parent_object_id'] = 'cat_'.$forum['cat_id'];
		} else {
			$forum['parent_object_id'] = 'forum_'.$forum['parent_forum_id'];
		}

		$this->view->assign('forum',$forum);

		$access_model = & Model::getInstance('AccessModel');
		if (isset($forum['forum_id'])) {
			$groups = $access_model->getForumGroups($forum_id);
			$groups = parseTree($groups, 0, 0,'id','parent_id', true);
		} else {
			$groups = array();
		}

		foreach ($groups as $group_id => $group) {
			$groups[$group_id]['permissions'] = array();
			$permissions = $access_model->getForumGroupPermissions($forum_id,$group['id']);
			foreach ($permissions as $role_row) {
				$role_id = $role_row['role_id'];
				unset($role_row['id']);
				unset($role_row['role_id']);
				$groups[$group_id]['permissions'][$role_id]=array();
				foreach ($role_row as $access_name => $access_value) {
					if ($access_value > 0) {
						$groups[$group_id]['permissions'][$role_id][] = $access_name;
					}
				}
			}
			
			$default_permissions = array();
			foreach ($access_model->access as $perm_name) {
				$default_permissions[$perm_name] = 1;
			}

			foreach ($access_model->roles as $role_id=>$role_name) {
				if (!isset($groups[$group_id]['permissions'][$role_id])) {
					$access_model->setForumGroupPermissions($forum_id, $group['id'], $role_id, $default_permissions);
					$groups[$group_id]['permissions'][$role_id] = $access_model->access;
				}
			}

		}
		$roles = array();
		foreach ($access_model->roles as $role_id => $role_name) {
			$roles[$role_id] = Agora::lang(str_replace('AGORA_ROLE_', '', $role_name));
		}
		
		// new in joopport
		$quest_model = & Model::getInstance('JoopquestionsModel');
		
		$knames = $quest_model->get_kit_names();
		
		$this->view->assign('knames',$knames);
		
		if (!isset($forum_model)) {
			$forum_model = &Model::getInstance('ForumModel');
		}
		$kit_name = $forum_model->joop_getQuest($forum_id);
		
		
		if ($quest_model->kit_exists($kit_name)) {
			$questenable = 1;
		}
		else {
			$questenable = 0;
		}
		
		$this->view->assign('questenable', $questenable);
		$this->view->assign('old_kitname', $kit_name);
		
		//end of joopport
		
		
		$this->view->assign('roles', $roles);
		$this->view->assign('groups',$groups);

		$this->view->template = 'forums/forum';
	}

	function add_group()
	{
		$forum_id = Agora::getVar('forum_id');

		$access_model = & Model::getInstance('AccessModel');
		$forum_groups = $access_model->getForumGroups($forum_id);

		$group_model = & Model::getInstance('GroupModel');

		$groups = $group_model->loadAll();

		foreach ($groups as $grp_key => $group) {
			foreach ($forum_groups as $forum_group) {
				if ($group['id'] == $forum_group['id']) {
					// Temp work around.
					// Unsetting hides the group in the Add Group window
					// Selecting a Group which is already added has no ill effects
					
					//unset($groups[$grp_key]);
					
					$groups[$grp_key]['name'] = $groups[$grp_key]['name'] . ' *';
				}
			}
		}

		$groups = parseTree($groups,0,0,'id','parent_id', true);
		$this->view->assign('groups',$groups);

		$this->view->assign('forum_id',$forum_id);
		$this->view->template = 'forums/group';
	}

	function save_group()
	{
		$form = Agora::getPostVar('form');
		$forum_id = $form['forum_id'];
		$group_ids = Agora::getPostVar('group_id');
		
		if(is_array($group_ids) && count($group_ids) > 0)
		{
			$group_model =  & Model::getInstance('GroupModel');
			$access_model = & Model::getInstance('AccessModel');
			
			// Automatically add all top level groups
			/*
			if ($parent = $group_model->getParent($group_id)) 
			{
				$grps = $access_model->getForumGroups($forum_id);
				$forum_groups = array();
				foreach ($grps as $key => $grp) 
				{
					$forum_groups[] = $grp['id'];
				}
				
				if (!in_array($parent,$forum_groups))
				{
					JError::raiseNotice( 0, JText::_('Sorry you need to select the Parent group First. The Chicken REALLY did come before the egg') );
					$this->redirect('action=edit_forum','forum_id='.$forum_id);
				}
			} // end if has parent
			*/
			foreach($group_ids as $group_id) {
				$access_model->addForumGroup($forum_id,$group_id);
			}
		} else {
			JError::raiseNotice( 0, JText::_('NO CHANGES MADE') );
		}

		$this->redirect('action=edit_forum','forum_id='.$forum_id);
	}

	function delete_groups()
	{
		
		$form = Agora::getPostVar('form',array());
		$cid = Agora::getPostVar('cid',array());
		$forum_id = $form['forum_id'];
		$access_model = &Model::getInstance('AccessModel');
		$group_model = & Model::getInstance('GroupModel');		
		
		foreach ($cid as $group_id) {
			
			if ($children = $group_model->getChildren($group_id)) 
			{
				$grps = $access_model->getForumGroups($forum_id);
				$forum_groups = array();
				foreach ($grps as $key => $grp) 
				{
					$forum_groups[] = $grp['id'];
				}
				if (array_intersect($children,$forum_groups)) 
				{
					JError::raiseWarning( 0, JText::_('Sorry, you need to remove all Child Groups first!') );
					$this->redirect('action=edit_forum','forum_id='.$forum_id);
				}
				else
				{
					$access_model->deleteForumGroup($forum_id,$group_id);
				}

			} 
			else 
			{
				$access_model->deleteForumGroup($forum_id,$group_id);
			}
		}
		$this->redirect('action=edit_forum','forum_id='.$forum_id);
	}
	
	function edit_permissions()
	{
		$group_id = Agora::getVar('group_id');
		$forum_id = Agora::getVar('forum_id');
		$role_id = Agora::getVar('role_id');

		$access_model = & Model::getInstance('AccessModel');

		$forum_perm = $access_model->getForumGroupPermissions($forum_id,$group_id);
		foreach ($forum_perm as $perm) {
			if ($perm['role_id'] == $role_id) {
				$forum_perm = $perm;
				break;
			}
		}
		unset($forum_perm['id']);
		unset($forum_perm['role_id']);

		$this->view->assign('permissions',$forum_perm);

		$this->view->assign('group_id',$group_id);
		$this->view->assign('forum_id',$forum_id);
		$this->view->assign('role_id',$role_id);
		
		$this->view->template = 'forums/permissions';
	}

	function save_permissions()
	{
		$form = Agora::getPostVar('form');
		$group_id = $form['group_id'];
		$forum_id = $form['forum_id'];
		$role_id = $form['role_id'];

		$access_model = & Model::getInstance('AccessModel');
		$forum_perm = $access_model->getForumGroupPermissions($forum_id,$group_id);
		foreach ($forum_perm as $perm) {
			if ($perm['role_id'] == $role_id) {
				$forum_perm = $perm;
				break;
			}
		}
		unset($forum_perm['id']);
		unset($forum_perm['role_id']);

		foreach ($forum_perm as $permission=>$value) {
			$forum_perm[$permission] = 0;
		}

		foreach ($form as $perm_name=>$permission) {
			// $form has other data except permissions - role_id, group_id, etc.
			// here we ensure we update permission only
			if (isset($forum_perm[$perm_name]))
				$forum_perm[$perm_name] = 1;
		}		

		$access_model->setForumGroupPermissions($forum_id,$group_id,$role_id,$forum_perm);
		$this->redirect('action=edit_forum','forum_id');

	}

	function add_forum()
	{
	    $styles_model = & Model::getInstance('StylesModel');
		$styles = $styles_model->_loadAll();
		$styling=array();
		$styling[0]='default';
		foreach ($styles as $style) {
			$styling[$style['id']] = $style['ref_name'];
		}
		$this->view->assign('styling',$styling);
	    
		$parents = array();
		foreach ($this->forumList as $category) {
			$parents['cat_'.$category['cat_id']] = $category['cat_name'];
			foreach ($category['forums'] as $forum) {
				$parents['forum_'.$forum['id']] = str_repeat('&nbsp;&nbsp;',$forum['level']+1).$forum['forum_name'];
			}
		}

		$forum = array(
			'enable' => '1', 'icon_style_id'=>0
		);

		if (count($parents)) {
			$ids = array_keys($parents);
			$forum['parent_object_id'] = $ids[0];
		}

		$guest_access = array('Disabled','Enabled','Enabled with captcha');
		$guest_access = array_map(array('Agora','lang'), $guest_access);
		$this->view->assign('guest_access',$guest_access);

		$this->view->assign('forum',$forum);
		$this->view->assign('parents',$parents);
		$this->view->template = 'forums/forum';
	}

	function apply_forum()
	{
		$forum_id = $this->__save_forum_changes();
		if ($forum_id)
			$this->redirect('action=edit_forum','forum_id='.$forum_id);
	}

	function save_forum()
	{
		if ($this->__save_forum_changes())
			$this->redirect();
	}

	function __save_forum_changes()
	{
		$forum_model = & Model::getInstance('ForumModel');

		$form = Agora::getPostVar('form',array());

		//new in joopport
		if (!$form['questenable'] or trim($form['quest_group']) == '') {
			$form['quest_group'] = '';			
		}
		unset($form['questenable']);	
		//end of joopport
		
		if (!isset($form['parent_object'])) {
			Agora::showError(Agora::lang('Please select parent object'));
			$this->edit_forum($form);
			return false;
		}

		$parent = $form['parent_object'];

		if (!preg_match('/(\w+)_(\d+)/',$parent,$matches)) {
			Agora::showMessage('Invalid form');
			$this->edit_forum($form);
			return false;
		}

		if ($matches[1] === 'cat') {
			$form['cat_id'] = $matches[2];
			$form['parent_forum_id'] = 0;
		} elseif ($matches[1] === 'forum') {
			$form['parent_forum_id'] = $matches[2];
			$form['cat_id'] = $forum_model->getCategory($matches[2]);
		} else {
			Agora::addMessage('Bad request');
			return false;
		}
		
		$moderation_model = & Model::getInstance('ModerationModel');
		if ($form['use_moderation'] == 0 && $moderation_model->checkUnapproved((int)$form['forum_id'])) {
			Agora::showError(Agora::lang('MODERATION_CANNOT_SWITCHOFF'));
			$this->edit_forum($form);
			return false;		
		}

		if (!isset($form['forum_name']) || empty($form['forum_name'])) {
			Agora::showError(Agora::lang('Forum name cannot be empty'));
			$this->edit_forum($form);
			return false;
		}

		if (isset($form['forum_id'])) {
			$forum_id = $form['forum_id'];
			
			// to update cat_id in possible subforums
			$cat_id = $forum_model->getCategory($forum_id);
			if ($cat_id != $form['cat_id']) {
				// we moved forum to another category
				// cat_id should be updated for subforums
				$forum_model->updateChildrenCategory($forum_id, $form['cat_id']);
			}

			unset($form['forum_id']);
			unset($form['parent_object']);
			$forum_model->edit($forum_id, $form);
		} else {
			$forum_id = $forum_model->add($form);
		}

		$access_model = & Model::getInstance('AccessModel');
		
		if ($access_model->getForumGroupCount($forum_id) == 0) {
			$access_model->addForumGroup($forum_id,1);
		}

		Agora::showMessage(Agora::lang('Forum saved'));
		return $forum_id;
	}
	
	function edit_category()
	{
		$category_model = & Model::getInstance('CategoryModel');
		$styles_model = & Model::getInstance('StylesModel');
		$category_model->reorder();
		$categories = $category_model->loadAll();
		$order = array();
		foreach ($categories as $category) {
			$order[$category['disp_position']] = $category['cat_name'];
		}
		$this->view->assign('ordering',$order);
		
		$styles = $styles_model->_loadAll();
		$styling=array();
		$styling[0]='default';
		foreach ($styles as $style) {
			$styling[$style['id']] = $style['ref_name'];
		}
		$this->view->assign('styling',$styling);		

		$category_id = Agora::getVar('category_id');
		$category = $category_model->load($category_id);
		$icon_style = $category_model->getIconSyleData($category["icon_style_id"]);
		$category["ref_name"]=$icon_style["ref_name"];
		$this->view->assign('category',$category);

		$this->view->template = 'forums/category';
	}

	function add_category()
	{
		$category_model = & Model::getInstance('CategoryModel');
		$styles_model = & Model::getInstance('StylesModel');
		$category_model->reorder();
		$categories = $category_model->loadAll();
		$order = array();
		foreach ($categories as $category) {
			$order[$category['disp_position']] = $category['cat_name'];
		}
		
		$styles = $styles_model->_loadAll();
		$styling=array();
		$styling[0]='default';
		foreach ($styles as $style) {
			$styling[$style['id']] = $style['ref_name'];
		}
		$this->view->assign('styling',$styling);		
		
		$category = array('cat_name'=>'', 'icon_style_id'=>0);
		$this->view->assign('category',$category);
		
		$this->view->assign('ordering',$order);
		$this->view->template = 'forums/category';
	}

	function save_category()
	{
		$form = Agora::getPostVar('form',array());
		$category_model = & Model::getInstance('CategoryModel');
		
		if (isset($form['category_id'])) {
			$category_id = $form['category_id'];
			unset($form['category_id']);
			$category_model->edit($category_id, $form);
		} else {
			$category_model->add($form, $form['disp_position']);
		}
		$this->redirect();
	}

	function cat_enable()
	{
		$cat_list = Agora::getPostVar('cid',array());
		if (!is_array($cat_list) || count($cat_list) == 0) {
			$this->redirect();
		}

		$id = array_shift($cat_list);
		$id = substr($id,9);
		$category_model = & Model::getInstance('CategoryModel');
		$category_model->enable($id);
		$this->redirect();
	}

	function cat_disable()
	{
		$cat_list = Agora::getPostVar('cid',array());
		if (!is_array($cat_list) || count($cat_list) == 0) {
			$this->redirect();
		}

		$id = array_shift($cat_list);
		$id = substr($id,9);
		$category_model = & Model::getInstance('CategoryModel');
		$category_model->disable($id);
		$this->redirect();
	}

	function forum_enable()
	{
		$forum_list = Agora::getPostVar('cid',array());
		if (!is_array($forum_list) || count($forum_list) == 0) {
			$this->redirect();
		}

		$id = array_shift($forum_list);
		$id = substr($id,6);
		$forum_model = & Model::getInstance('ForumModel');
		$forum_model->enable($id);
		$this->redirect();
	}

	function forum_disable()
	{
		$forum_list = Agora::getPostVar('cid',array());
		if (!is_array($forum_list) || count($forum_list) == 0) {
			$this->redirect();
		}

		$id = array_shift($forum_list);
		$id = substr($id,6);
		$forum_model = & Model::getInstance('ForumModel');
		$forum_model->disable($id);
		$this->redirect();
	}

	function remove_proceed()
	{
	    $form = Agora::getPostVar('form');
	    $cid = Agora::getPostVar('cid');
		$category_model = &Model::getInstance('CategoryModel');
		$forum_model = &Model::getInstance('ForumModel');
		
		// Remove
	    if ((int)$form['operation'] == 1)
	    {
		  foreach ($cid as $id) {
			if (strpos($id,'category_') === 0) {
				$cat_id = substr($id,9);
				$category_model->delete($cat_id);
			} elseif (strpos($id,'forum_') === 0) {
				$forum_id = substr($id,6);
				$forum_model->delete($forum_id);
			}
		  }
		  	        
	    }
		// Move
	    else if((int)$form['operation'] == 2)
	    {
			if (strpos($cid[0],'category_') === 0) {
				$cat_id = substr($cid[0],9);
				$category_model->moveForumsTo($cat_id, Agora::getPostVar('moveto'));
			} elseif (strpos($cid[0],'forum_') === 0) {
				$forum_id = substr($cid[0],6);
				$forum_model->moveTopicsTo($forum_id, Agora::getPostVar('moveto'));
			}
	        
	    }
	    $this->redirect();
	}
	function remove()
	{
		$cid = Agora::getPostVar('cid');
		
		$operations[1]=JText::_('Remove');
		if ( count($cid) == 1 )
		{
		    $operations[2]=JText::_('Move to');
		    if (strpos($cid[0],'category_') === 0){
		    $this->view->assign('cid_type','category');
		    $this->view->assign('cid_id',substr($cid[0],9));
		    }
		    elseif (strpos($cid[0],'forum_') === 0){
		    $this->view->assign('cid_type','forum');
		    $this->view->assign('cid_id',substr($cid[0],6));
		    }
		}
		
		$this->view->assign('cid',$cid);		
		$this->view->assign('operation',$operations);
		$this->view->template = 'forums/remove';

	}
	
	//JOOPPORT FUNCTIONS
	function joopport_enable()
	{
		$forum_list = Agora::getPostVar('cid',array());
		if (!is_array($forum_list) || count($forum_list) == 0) {
			$this->redirect();
		}

		$id = array_shift($forum_list);
		$id = substr($id,6);
		$forum_model = & Model::getInstance('ForumModel');
		$forum_model->joop_enable($id);
		$this->redirect();
	}

	function joopport_disable()
	{
		$forum_list = Agora::getPostVar('cid',array());
		if (!is_array($forum_list) || count($forum_list) == 0) {
			$this->redirect();
		}

		$id = array_shift($forum_list);
		$id = substr($id,6);
		$forum_model = & Model::getInstance('ForumModel');
		$forum_model->joop_disable($id);
		$this->redirect();
	}
}

?>
